const express = require('express');
const router = express.Router();
const { User } = require('../models');
const { where } = require('sequelize');
const { failure, success } = require('../utils/responses');
const { NotFoundError, BadRequestError, UnauthorizedError } = require('../utils/errors');
const bcrypt = require('bcryptjs');
const { Op } = require('sequelize');
const jwt = require('jsonwebtoken');

//用户注册
router.post('/register', async (req, res) => {
    try {
        const body = {
            email: req.body.email,
            username: req.body.username,
            nickname: req.body.nickname,
            password: req.body.password,
            sex: 2,
            role: 0
        }
        const user = await User.create(body);
        //删除返回的密码
        delete user.dataValues.password;

        success(res, '用户注册成功，请返回登录页面进行登录', { user }, 201)
    } catch (error) {
        failure(res, error);
    }

})

//用户登录
router.post('/login', async (req, res) => {
    try {
        const { login, password } = req.body;
        if (!login) {
            throw new BadRequestError('用户名不能为空');
        }
        if (!password) {
            throw new BadRequestError('密码不能为空');
        }

        //查询用户中是否存在该用户
        const condition = {
            where: {
                [Op.or]: [
                    { email: login },
                    { username: login }
                ]
            }
        }
        const user = await User.findOne(condition);
        if (!user) {
            throw new NotFoundError('用户不存在');
        }

        const isPasswordValid = bcrypt.compareSync(password, user.password);
        if (!isPasswordValid) {
            throw new UnauthorizedError('密码错误');
        }

        //生成token
        const token = jwt.sign({
            userId: user.id,
        }, process.env.SECRET, { expiresIn: '30d' })
        success(res, '用户登录成功', { token }, 200)
    } catch (error) {
        failure(res, error);
    }
})

module.exports = router;